const { setLastError, success, warn, getPrint } = require("../utils/log_tool");
const { BaseCommand } = require("./base");
const { formatData } = require("./share_data");

class WatchMailCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        await new Promise((resolve, _reject) => {
            const MailWatcher = require("mail-watcher");
            // IMAP： 默认端口：143 （ssl安全链接端口：993）
            // SMTP： 默认端口：25 （ssl安全链接端口：994）
            // POP3： 默认端口：110 （ssl安全链接端口：995）
            const imap = {
                user: data.user,
                password: data.password,
                host: data.host,
                port: data.port || (data.tls ? 993 : 143), // imap port
                tls: data.tls, // use secure connection
                // search: ['ALL'],
                // search: ['UNSEEN'],
                search: data.search || ["UNSEEN"],
                tlsOptions: {
                    rejectUnauthorized: false,
                },
            };
            const mailWatcher = MailWatcher(imap);
            const cache_mail_ids = [];
            // const fs = require("fs");
            mailWatcher
                .on("end", () => {
                    warn(`restart ...`);
                    mailWatcher.start();
                })
                .on("connected", () => {
                    resolve();
                })
                .on("error", (err) => {
                    setLastError(err);
                    resolve();
                })
                .on(
                    "mail",
                    /**
                     *
                     * @param {import('../lib').ParsedMail} mail
                     */
                    async (mail) => {
                        const subject = mail.subject;
                        const text =
                            mail.text ||
                            require("html-to-text").convert(mail.html);
                        const id = mail.messageId;
                        // 值映射
                        const value_mapping = data.value_mapping;
                        let index = cache_mail_ids.indexOf(id);
                        if (index === -1) {
                            index = cache_mail_ids.length;
                            cache_mail_ids.push(id);
                        }
                        const mailData = {
                            index: index,
                            id,
                            subject,
                            text,
                        };
                        if (value_mapping) {
                            if (typeof value_mapping === "string") {
                                this.shareData[value_mapping] = mailData;
                            }
                        } else {
                            this.shareData.mail_data = mailData;
                        }
                        if (data.verbose) {
                            success("");
                            success(getPrint(mailData));
                        }
                        let commandCfgs = data.commands;
                        if (commandCfgs) {
                            // 特殊处理字符的情况
                            if (typeof commandCfgs === "string") {
                                commandCfgs = formatData(commandCfgs);
                            }
                            // 默认从循环开始执行，增加深度
                            await this.exec(commandCfgs, this.depth + 1);
                        }
                    },
                )
                .start();
        });
    }
}

module.exports = {
    WatchMailCommand,
};
